//
//  PlayNumSearchVC.swift
//  ImGuider X
//
//  Created by 王鹏宇 on 10/8/18.
//  Copyright © 2018 imguider. All rights reserved.
//

import UIKit

class PlayNumSearchVC: BasePlayVC,PlayBarDelegate,UICollectionViewDelegate,UICollectionViewDataSource {
    
    let BoardHeight = (ISiPhone5 || ISiPhone4) ? 140 : 188
    let TextHeight = 40
    let TipHeight : CGFloat = 40
    
    var viewmodel:PlayViewModel = PlayViewModel()
    
    @IBOutlet weak var bgView: UIView!
    
    @IBOutlet weak var collectionView: UICollectionView!
    
    @IBOutlet weak var tipLabel: UILabel!
    @IBOutlet weak var numTextfield: UITextField!
    
    @IBOutlet weak var menuView: UIView!
    @IBOutlet weak var keyBoardView: UIView!
    @IBOutlet weak var foldView: UIView!
    
    @IBOutlet weak var keyBoardHeight: NSLayoutConstraint!
    @IBOutlet weak var tipHeight: NSLayoutConstraint!
    @IBOutlet weak var searchHeight: NSLayoutConstraint!
    
    @IBOutlet weak var playView: UIView!
    var changeMapBtn : UIButton?
    
    var backBtn : UIButton!
    
    var pageView : OtherDetailHeadView!
    var playBar : PlayBar!
    var dropListView : X_DropListView!
    var imageView : UIImageView = UIImageView()
    var maskView : UIView = UIView()
    var isSearchOrAllPoint : Bool = true
    var isAll : Bool = false
    var bgUrl : String?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setup()
        setupKeyBoardView()
        setupMaskView()
        configNav()
        self.maskViewAppear()
        setupData()
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        if !isPlayAlways {
            WPY_AVPlayer.playManager.stop()
        }
    }
    
}



extension PlayNumSearchVC {
    
    func setup(){
        
        self.title = LocalizedString("search_id")
        self.setNavBarStyle(.transparency)
        playBar = PlayBar(frame: CGRect(x: 0, y: 0, width: kScreenWidth, height: 120))
        playBar.delegate = self
        self.playView.addSubview(playBar)
        
        self.menuView.layer.cornerRadius = 20.0
        self.menuView.clipsToBounds = true
        
        pageView = OtherDetailHeadView(frame: CGRect(x: 0, y: 0, width: kScreenWidth, height: kScreenHeight - kTableBarHeight - 102))
        self.bgView.insertSubview(pageView, belowSubview: self.foldView)
        
        pageView.selectIndex = {
            
            [weak self] index in
            guard let `self` = self else { return }
            
            if self.changeMapBtn?.isSelected ?? false{
                
                if let count = self.viewmodel.line?.mapPicArray?.count, count > 0 {
                    
                    self.setupBrowser(images:self.viewmodel.line?.mapPicArray, index: index) { (next) -> UIView? in
                        
                        return  self.pageView
                    }
                }
                
            }else  {
                self.maskViewAppear()
                self.showSearchOrAllPoint(isShow: self.isSearchOrAllPoint)
            }
            
        }
        
        pageView.pageControl.snp.remakeConstraints {
            
            [weak self] maker in
            guard let `self` = self else { return }
            
            maker.left.equalToSuperview()
            maker.right.equalToSuperview()
            maker.bottom.equalTo(self.foldView.snp.top)
            maker.height.equalTo(30)
        }
        
        if let collectionLayout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout {
            
            let width = (kScreenWidth - 64)/3
            collectionLayout.itemSize = CGSize(width: width, height: width + 32)
            collectionLayout.minimumLineSpacing = 0
            collectionLayout.minimumInteritemSpacing = 16
            collectionLayout.sectionInset = UIEdgeInsets(top: 0, left: 16, bottom: 0, right: 16)
        }
        
        self.collectionView.register(UINib(nibName: "SearchRecordCell", bundle: nil), forCellWithReuseIdentifier: "SearchRecordCell")
        
        //        self.closeAutomaticallyInsets(scrollview:)
        self.numTextfield.inputView = UIView(frame: CGRect.zero)
        self.numTextfield.keyboardToolbar.isHidden = true
        
        self.dropListView = X_DropListView.SetupDropListView(frame: CGRect(x: kScreenWidth - 115, y: kNavigationBarHeight - 15, width: 110, height: 60), typeList: [ListType.LoopBtnType], contentView: self.view)
        
        
    }
    
    func configNav(){
        
        backBtn = UIButton(frame: CGRect(x: 0, y: 0, width: 44, height: 44))
        backBtn.setImage(UIImage(named: "back"), for:.normal)
        backBtn.setImage(UIImage(named: "close"), for: .selected)
        backBtn.addTarget(self, action: #selector(goBack(sender:)), for: .touchUpInside)
        let leftItem =   UIBarButtonItem(customView: backBtn)
        self.navigationItem.leftBarButtonItem = leftItem
        
        let rightItem = UIBarButtonItem(image: UIImage(named:"more"), style: .plain, target: self, action: #selector(goMore))
        self.navigationItem.rightBarButtonItem = rightItem
    }
    
    func setupMaskView(){
        
        self.bgView.insertSubview(self.maskView, belowSubview: self.foldView)
        self.maskView.snp.makeConstraints { (make) in
            make.top.bottom.left.right.equalToSuperview()
        }
        self.maskView.addSubview(self.imageView)
        self.imageView.contentMode = .scaleAspectFill
        self.imageView.snp.makeConstraints { (make) in
            make.top.bottom.left.right.equalToSuperview()
        }
        
        let tap = UITapGestureRecognizer(target: self, action: #selector(maskViewDissappear(Animation:)))
        self.maskView.addGestureRecognizer(tap)
        
        
        if let bgimage = UIImage(named: "bg"){
            self.imageView.image = bgimage.blurredImage(withRadius: 25, iterations: 5, tintColor: UIColor.black)
        }
        
        
        
    }
    
    @objc func goMore(){
        
        if self.dropListView.isHidden {
            self.dropListView.show()
        }else{
            self.dropListView.hidde()
        }
        
    }
    
    @objc func maskViewDissappear(Animation : Bool){
        
        self.setNavBarStyle(.translucence)
        self.tipLabel.text = ""
        self.keyBoardHeight.constant = 0.0
        self.searchHeight.constant = 0.0
        self.numTextfield.isHidden = true
        self.maskView.isHidden = true
        self.collectionView.isHidden = true
        self.backBtn.isSelected = false
        self.title = self.viewmodel.currentRecord?.spotname
        if Animation {
            UIView.animate(withDuration: 0.3, animations: {
                self.view.layoutIfNeeded()
            }) { (finished) in
                
                self.keyBoardView.isHidden = true
            }
        }else{
            self.keyBoardView.isHidden = true
        }
    }
    
    func maskViewAppear(){
        self.setNavBarStyle(.transparency)
        if let placeholder = UIImage(named: "bg"){
            
            
            if let url = self.viewmodel.currentPics?.first  {
                self.imageView.kf.setImage(with:URL(string: url), placeholder: placeholder, options: nil, progressBlock: nil) {
                    
                    [weak self] (image, _, _, _) in
                    
                    self?.imageView.image = image?.blurredImage(withRadius: 25, iterations: 5, tintColor: UIColor.black)
                }
            }
        }
        //|| self.viewmodel.records?.count > 0
        //        self.imageView.image = UIImage(named: "bg")
        if !self.isSearchOrAllPoint {
            self.collectionView.isHidden = false
        }
        
        if let count = self.viewmodel.resultArray?.count, count > 0 {
            self.collectionView.isHidden = false
        }
        self.maskView.isHidden = false
        self.backBtn.isSelected = true
        
    }
    func setupKeyBoardView(){
        
        let btnArr:[String] = ["1","2","3","4","5","6","7","8","9","0","删除"]
        let Hspace = 16
        let Vspace = 11
        let width = (kScreenWidth - 64) / 3
        let Height = ((ISiPhone5 || ISiPhone4) ? (140 - 44)/4  : (188 - 44)/4)
        var Y = 0
        for i in 0..<btnArr.count{
            
            Y = Int(i/3) * (Vspace + Height)
            let num = i%3
            let str = btnArr[i]
            let btn = UIButton(frame: CGRect(x: Hspace + num * (Hspace + width), y: Y, width: width, height: Height))
            btn.layer.borderWidth = 1.0
            btn.layer.borderColor = UIColor.hexStringToColor(hexString: "#707070").withAlphaComponent(0.5).cgColor
            btn.setTitle(str, for: .normal)
            btn.setTitleColor(UIColor.hexStringToColor(hexString: "#222222").withAlphaComponent(0.5), for: .normal)
            btn.titleLabel?.font = UIFont.systemFont(ofSize: 18)
            if (str == "删除"){
                btn.setImage(UIImage(named: "search-grey"), for: .normal)
                btn.backgroundColor = UIColor.hexStringToColor(hexString: "#222222").withAlphaComponent(0.12)
                btn.setTitle("", for: .normal)
                btn.layer.borderWidth = 0
                btn.frame = CGRect(x: Hspace + 2 * (Hspace + width), y: Y, width: width, height: Height)
            }else if(str == "0"){
                btn.frame = CGRect(x: Hspace, y: Y, width: width * 2 + Hspace, height: Height)
            }
            
            btn.addTarget(self, action: #selector(keyAction(sender:)), for: .touchUpInside)
            self.keyBoardView.addSubview(btn)
            
        }
        
    }
    
    @objc func keyAction(sender : UIButton){
        
        var str = self.numTextfield.text ?? ""
        
        if sender.currentTitle?.count == 0 {
            
            if str.count >= 1{
                
                let index = str.index(str.startIndex, offsetBy: str.count - 1)
                
                self.numTextfield.text = String(str.prefix(upTo: index))
            }else if str.count == 0 {
                
                self.tipLabel.text = ""
                self.collectionView.reloadData()
                self.collectionView.isHidden = true
            }
        }else{
            if str.count < 5 {
                if let char = sender.currentTitle {
                    str.append(char)
                    self.numTextfield.text = str
                }
            }
        }
        
        if str.count > 2 {
            if let searchText = self.numTextfield.text {
                self.viewmodel.searchNodeNumberWith(searchText:searchText)
            }
        }
        
    }
    
    func setupMenuView(){
        
        self.menuView.backgroundColor = UIColor.white
        self.menuView.layer.cornerRadius = 20
        self.menuView.clipsToBounds = true
        
        let width = kScreenWidth / viewmodel.menuTagsArray.count
        
        for i in 0 ..< viewmodel.menuTagsArray.count {
            
            let btn = UIButton(type: .custom)
            btn.frame = CGRect(x: i * width, y: 0, width: width, height: 60)
            self.menuView.addSubview(btn)
            
            let type = viewmodel.menuTagsArray[i]
            
            switch(type){
                
            case .MenuTypeCamera:
                btn.setImage(UIImage(named: "cameraMenu"), for: .normal)
                btn.addTarget(self, action: #selector(goCamera), for: .touchUpInside)
            case .MenuTypeMap:
                btn.setImage(UIImage(named: "mapMenu"), for: .normal)
                btn.setImage(UIImage(named: "imageMenu"), for: .selected)
                self.changeMapBtn = btn
                btn.addTarget(self, action: #selector(changeMapModel(sender:)), for: .touchUpInside)
            case .MenuTypeSearch:
                btn.setImage(UIImage(named: "searchMenu"), for: .normal)
                btn.addTarget(self, action: #selector(goSearch), for: .touchUpInside)
            case .MenuTypeNode:
                btn.setImage(UIImage(named: "listMenu"), for: .normal)
                btn.setImage(UIImage(named: "键盘"), for: .selected)
                btn.addTarget(self, action: #selector(changeTab(sender:)), for: .touchUpInside)
                
            default:
                break
            }
        }
    }
    
    func setupData(){
        
        viewmodel.reloadData()
        
        viewmodel.loadFinished = {
            
            [weak self] errmsg in
            guard let `self` = self else { return }
            
            if let errmsg = errmsg {
                
                self.view.makeToast(errmsg)
                
            }
            
            self.collectionView.reloadData()
            self.setupMenuView()
            self.maskViewAppear()
            if let count = self.viewmodel.records?.count , count > 0 {
                WPY_AVPlayer.playManager.musicArray = self.viewmodel.records!
                WPY_AVPlayer.playManager.lineModel = self.viewmodel.line
                
                self.selectCellWithIndex(index: 0, immediately: false)
            }
            
            
        }
        
        
        viewmodel.reloadRecord = {
            
            [weak self] in
            guard let `self` = self else { return }
            
            self.pageView.pics = self.viewmodel.currentPics
        }
        
        viewmodel.searchRelod = {
            
            [weak self] type in
            guard let `self` = self else { return }
            
            self.setSearchResult(resultState: type)
        }
        
        
        viewmodel.progressText = {
            
            [weak self] msg in
            guard let `self` = self else { return }
            
            self.playBar.downloadBtn.setTitle(msg, for: .normal)
            self.playBar.downloadBtn.setImage(nil, for: .normal)
        }
        
        viewmodel.refreshCollectionView = {
            [weak self] in
            guard let `self` = self else { return }
            
            self.collectionView.reloadData()
        }
    }
    
    func changeScenicPointWithIndex(index : Int){
        
        guard let record = self.viewmodel.records?[index] else {return}
        
        let indexPath = IndexPath(row: index, section: 0)
        
        if let cell = self.collectionView.cellForItem(at: self.viewmodel.currentIndexPath) as? RecordCell {
            cell.isSelect = false
        }
        
        if let currentCell = self.collectionView.cellForItem(at: indexPath) as? RecordCell {
            
            currentCell.isSelect = true
        }
        
        self.collectionView.reloadData()
        self.viewmodel.currentIndexPath = indexPath
        self.viewmodel.currentRecord = record
    }
    
    
    func selectCellWithIndex(index : Int,immediately : Bool){
        
        changeScenicPointWithIndex(index: index)
        self.playBar.playMusicWithIndex(index: index, immediately: immediately)
        
    }
    
    func setSearchResult(resultState : SearchResultType){
        
        //        if let arr = self.viewmodel.resultArray {
        //
        //        }
        
        switch resultState {
        case .NoResult:
            self.collectionView.isHidden = true
            if let str = self.numTextfield.text {
                self.tipLabel.text = String.localizedStringWithFormat(LocalizedString("search_id_faild"), str)
                self.tipHeight.constant = TipHeight
                //                self.tipLabel.isHidden = false
            }
            
        case .GetResult:
            self.tipLabel.text = LocalizedString("maybe_search_tips")
            self.tipLabel.isHidden = false
            self.tipHeight.constant = TipHeight
            self.collectionView.isHidden = false
            self.collectionView.reloadData()
        case .MaybeResult:
            self.tipLabel.text = LocalizedString("maybe_search_tips")
            self.tipLabel.isHidden = false
            self.tipHeight.constant = TipHeight
            self.collectionView.isHidden = false
            self.collectionView.reloadData()
            
        }
    }
    // 切换播放调整UI
    func changePointTo(index: Int) {
        
        self.changeScenicPointWithIndex(index: index)
    }
    
    //下载
    func downloadAction() {
        
        viewmodel.downloadTapped()
    }
    
    @objc func changeMapModel(sender : UIButton){
        self.maskViewDissappear(Animation: true)
        
        if !sender.isSelected {
            
            self.pageView.autoScroll = false
            self.pageView.imageContentMode = .scaleAspectFit
            self.pageView.pics = self.viewmodel.line?.mapPicArray
            sender.isSelected = true
            
        }else {
            
            self.pageView.autoScroll = true
            self.pageView.imageContentMode = .scaleAspectFill
            self.pageView.pics = self.viewmodel.currentPics
            sender.isSelected = false
        }
        
    }
    
    @objc func goCamera(){
        
        self.present(MyCamera(), animated: true, completion: nil)
    }
    
    
    @objc func goSearch(){
        
    }
    
    @objc func changeTab(sender : UIButton){
        
        self.maskViewAppear()
        if sender.isSelected {
            self.showSearchOrAllPoint(isShow: true)
            self.title = LocalizedString("search_id")
            sender.isSelected = false
        }else {
            self.showSearchOrAllPoint(isShow: false)
            self.title = LocalizedString("all_records")
            sender.isSelected = true
        }
    }
    
    func showSearchOrAllPoint(isShow : Bool){
        
        
        self.isSearchOrAllPoint = isShow;
        
        if isShow {
            
            self.isAll = false
            self.keyBoardHeight.constant = CGFloat(BoardHeight)
            self.keyBoardView.isHidden = false
            self.searchHeight.constant = CGFloat(TextHeight)
            self.numTextfield.isHidden = false
            
            if let count = self.viewmodel.resultArray?.count {
                if (count) > 0 {
                    
                    self.tipLabel.text = LocalizedString("maybe_search_tips")
                    self.tipHeight.constant = TipHeight
                    self.tipLabel.isHidden = false
                }
            }else {
                self.tipLabel.text = ""
                self.tipHeight.constant = TipHeight
                self.collectionView.isHidden = true
            }
            self.numTextfield.isHidden = false
        }else {
            
            self.isAll = true
            self.keyBoardHeight.constant = 0
            self.collectionView.isHidden = false
            self.title = LocalizedString("all_records")
            self.searchHeight.constant = 0
            self.numTextfield.isHidden = true
            self.tipLabel.text = ""
            self.tipHeight.constant = 0
        }
        
        UIView.animate(withDuration: 0.3, animations: {
            self.view.layoutIfNeeded()
        }) { (finished) in
            
            if isShow == false {
                self.keyBoardView.isHidden = true
            }
            self.collectionView.reloadData()
        }
    }
    
    @objc func goBack(sender : UIButton){
        
        if (sender.isSelected) {
            self.maskViewDissappear(Animation: true)
        }else {
            self.navigationController?.popViewController(animated: true)
        }
    }
    
    @objc func goShare(){
        
    }
}


extension PlayNumSearchVC {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        if !self.isAll {
            return self.viewmodel.resultArray?.count ?? 0
        }
        return self.viewmodel.records?.count ?? 0
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "SearchRecordCell", for: indexPath) as? SearchRecordCell else {return SearchRecordCell()}
        
        if isAll {
            
            if let record = self.viewmodel.records?[indexPath.row] {
                
                cell.configData(record: record)
                cell.isSelect = false
                if indexPath.row  == self.viewmodel.currentIndexPath.row {
                    cell.isSelect = true
                }
            }
        }else {
            if  let dd = self.viewmodel.resultArray?[indexPath.row] {
                
                cell.configData(record: dd)
                cell.isSelect = dd == viewmodel.currentRecord
            }
        }
        
        
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        if isAll {
            
            self.selectCellWithIndex(index: indexPath.row, immediately: true)
            maskViewDissappear(Animation: true)
        }else {
            
            if let record = self.viewmodel.resultArray? [indexPath.row]{
                
                guard let arr = self.viewmodel.records as NSArray? else{
                    return
                }
                let index = arr.index(of: record)
                self.selectCellWithIndex(index: index, immediately: true)
                maskViewDissappear(Animation: true)
            }
        }
    }
}
